#include <core/filesystem.h>
#include <ShlObj.h>

namespace Core
{
    namespace
    {
        String TemporaryPath;
    };
    String::Char Dir::PathSeparator = '\\';
    
    File* Dir::file(const String& s, IODevice::OpenMode om)
    {
        std::auto_ptr<File> file(new File);
        if (file->open(om, m_path + s))
        {
            return file.release();
        }
        return 0;
    }

    String Dir::pathFromFileName(const String& fileName)
    {
        return String();
    }

    //creates a new directory, trying to open existing first
    Dir* FileSystem::makeDir(const String& path)
    {
        if (Dir* d = openDir(path))
        {
            return d;
        }

        if (CreateDirectory(path.c_str(), 0))
        {
            return new Dir(path);
        }

        return 0;
    }

    Dir* FileSystem::openDir(const String& path)
    {
        DWORD fileAttr = GetFileAttributes(path.c_str());
        if (fileAttr & FILE_ATTRIBUTE_DIRECTORY)
        {
            return new Dir(path);
        }

        return 0;
    }

    String FileSystem::getSpecialPath(FileSystem::SpecialDirectory specialDir)
    {
        DWORD directoryFlags = 0;

        if (specialDir == FileSystem::TempDirectory)
        {
            if (TemporaryPath.empty())
            {
                boost::scoped_array<String::Char> buffer(new String::Char[MAX_PATH]);
                GetTempPath(MAX_PATH, buffer.get());
                TemporaryPath.assign(buffer.get());
            }
            return TemporaryPath;
        }
        switch(specialDir)
        {
        case FileSystem::PicturesDirectory:
            directoryFlags = CSIDL_MYPICTURES;
            break;
        case FileSystem::DocumentsDirectory:
            directoryFlags = CSIDL_COMMON_DOCUMENTS;
            break;
        case FileSystem::MusicDirectory:
            directoryFlags = CSIDL_COMMON_MUSIC;
            break;
        default:
            return String();
        };
        boost::scoped_array<String::Char> buffer(new String::Char[MAX_PATH]);
        if (FAILED(SHGetFolderPath(0, directoryFlags, 0, SHGFP_TYPE_CURRENT, buffer.get())))
        {
            return String();
        }
        return String(buffer.get());
    }
};
